/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *FileManageController
 * 文件记录
 *
 * 修改纪录
 * 2020-08-15 版本：1.0 donghang 创建。
 * @version 版本：1.0
 * @author 作者：donghang
 * 创建日期：2020-08-15
 */

package com.topscomm.meet.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.topscomm.basic.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.file.mq.FileProcessProducer;
import com.topscomm.meet.MeetSystemConst.FileUploadStateEnum;
import com.topscomm.meet.controller.auto.FileManageControllerAuto;
import com.topscomm.meet.pojo.FileManageEntity;
import com.topscomm.meet.service.impl.FileBlockRecordService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: donghang
 * @date: 2020-08-15
 * @description:文件记录Controller
 * @modify:
 */
@RestController
@RequestMapping("meet/fileManage")
public class FileManageController extends FileManageControllerAuto implements IFileManageController {
	/**
	 * 音视频存储路径
	 */
	@Value("${file.audio.root.path}")
	private String blockFolder;
	/**
	 * 文件块服务
	 */
	@Autowired
	FileBlockRecordService fileBlockRecordService;
	/**
	 * 文件处理消息生产
	 */
	@Autowired
	FileProcessProducer fileProcessProducer;

	/**
	 * @author: donghang
	 * @date: 2020-08-15
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_beginrecordtime")) {// 查询开始时间
			String value = paraMap.get("qry_beginrecordtime").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and recordtime >= {0} ", SQLAdapter.toDateLong(value));
		}
		if (paraMap.containsKey("qry_endrecordtime")) { // 查询结束时间
			String value = paraMap.get("qry_endrecordtime").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and recordtime <= {0} ", SQLAdapter.toDateLong(value));
		}
		if (paraMap.containsKey("qry_sourceid")) {
			String value = paraMap.get("qry_sourceid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourceid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_sourcetype")) {
			String value = paraMap.get("qry_sourcetype").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and sourcetype = '{0}' ", value);
		}
		return sql.toString();
	}

	/**
	 * @author: donghang
	 * @date: 2020-08-15
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * 重写文件查询，显示已上传进度
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年8月23日下午9:45:23
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/list")
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			if (!paraMap.containsKey("qry_sourceid")) {
				throw new ServiceException("id缺失");
			}
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			int totalCount = this.service.getCount1(paraMap, "queryFileList");
			// 分页拦截处理
			int beginCount = query.getCurrentPage() * query.getPageSize() - query.getPageSize();
			paraMap.put("begincount", beginCount);
			paraMap.put("pagesize", query.getPageSize());
			paraMap.put("IsNeedPage", true);
			List<Map<String, Object>> tempList = null;
			tempList = this.service.queryMap(paraMap, "queryFileList");
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * 文件块上传
	 *
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年8月17日上午9:07:51
	 * @modify:
	 */
	@PostMapping(value = "/uploadFileBlock")
	public ResponseResult<Object> uploadFileBlock(@RequestParam("file") MultipartFile file,
			@RequestParam(required = false) Map<String, Object> dataMap) {
		try {
			dataMap.put("usercode", this.getUserBean().getUser().getCode());
			dataMap.put("username", this.getUserBean().getUser().getName());
			// 上传文件块
			this.service.uploadFileBlock(file.getBytes(), dataMap);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		return ResponseResult.ok(dataMap);
	}

	/**
	 * 合并文件块
	 *
	 * @description:
	 * @return
	 * @author: donghang
	 * @date: 2020年8月17日上午9:49:08
	 * @modify:
	 */
	@PostMapping(value = "/mergeFileBlocks")
	public ResponseResult<Object> mergeFileBlocks(@RequestBody(required = false) FileManageEntity fileManageEntity) {
		if (fileManageEntity.getTotalblockcount() == 0) {
			return ResponseResult.error("缺失文件分片的总数参数");
		}
		try {
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("qry_identifiers", fileManageEntity.getIdentifier());
			paraMap.put("qry_sourceid", fileManageEntity.getSourceid());
			paraMap.put("qry_sourcetype", fileManageEntity.getSourcetype());
			//
			Map<String, Object> uploadBlockMap = this.service.getUploadBlocks(paraMap)
					.get(fileManageEntity.getIdentifier());
			if (uploadBlockMap == null) {
				return ResponseResult.error("文件上传不完整，请重新上传");
			}
			List<Integer> uploadsBlock = (List<Integer>) (uploadBlockMap.get("uploadblocklist"));
			if (uploadsBlock == null || uploadsBlock.size() != fileManageEntity.getTotalblockcount()) {
				return ResponseResult.error("文件上传不完整，请重新上传");
			}
			// 异步处理消息，后续通过责任链进行文件的处理
			Map<String, Object> messageMap = new HashMap<String, Object>();
			messageMap.put("fileName", fileManageEntity.getName());
			messageMap.put("identifier", fileManageEntity.getIdentifier());
			messageMap.put("sourceid", fileManageEntity.getSourceid());
			messageMap.put("sourcetype", fileManageEntity.getSourcetype());
			messageMap.put("foldername",
					fileManageEntity.getIdentifier() + "-" + ConvertUtil.convertToString(fileManageEntity.getSourceid())
							+ ConvertUtil.convertToString(fileManageEntity.getSourcetype()));
			this.fileProcessProducer.send(messageMap);
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("uploadstate", FileUploadStateEnum.UploadFinish);
			StringBufferProxy sql = new StringBufferProxy();
			sql.appendSingle(" 1=1 ");
			sql.appendSingle(" and identifier = '{0}' and sourceid='{1}' and sourcetype='{2}'",
					fileManageEntity.getIdentifier(), fileManageEntity.getSourceid(), fileManageEntity.getSourcetype());
			// 更新文件记录
			this.service.updateByWhere(dataMap, sql.toString());
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
		return ResponseResult.ok("已接收合并消息");
	}

	/**
	 * 得到上传的文件块号,支持多个文件上传
	 *
	 * @description:
	 * @return 确实的块号，已逗号分割
	 * @author: donghang
	 * @date: 2020年8月20日下午2:19:50
	 * @modify:
	 */
	@GetMapping(value = "/queryUploadBlocks")
	public ResponseResult<Object> queryUploadBlocks(@RequestParam Map<String, Object> paraMap) {
		return ResponseResult.ok(this.service.getUploadBlocks(paraMap));
	}

	/**
	 * 删除
	 *
	 * @description:
	 * @param paraMap
	 * @return
	 * @author: donghang
	 * @date: 2020年9月12日上午12:04:01
	 * @modify:
	 */
	@Override
	@DeleteMapping(value = "/delete")
	public ResponseResult<Object> delete(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			this.service.deleteFile(paraMap);
			return ResponseResult.ok("删除成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
}
